<?php

namespace app\shop\library\delivery\implements;

use app\shop\library\delivery\DeliveryInterface;
use app\shop\library\ShopHelper;
use app\shop\library\ShopLogHelper;
use Exception;
use GuzzleHttp\Client;
use Throwable;

class Kd100Implement implements DeliveryInterface
{
    private string $queryUrl = 'https://poll.kuaidi100.com';

    /**
     * @var array|mixed
     */
    private mixed $options;

    /**
     * @throws Exception
     */
    public function __construct()
    {
        $this->options = ShopHelper::get_setting_group('kd100_group');

        if (empty($this->options['kd100_key']) || empty($this->options['kd100_customer'])) {
            throw new Exception('快递100配置异常,请联系管理员');
        }
    }

    /**
     * 实时查询
     * @param array $params
     * @return array
     */
    public function query(array $params): array
    {
        $param         = [
            'customer' => $this->options['kd100_customer'],
            'param'    => json_encode([
                'num'      => $params['delivery_no'],
                'com'      => $params['delivery_company_code'],
                'phone'    => $params['receiver_phone'],
                'resultv2' => 4,
            ])
        ];
        $param['sign'] = strtoupper(md5($param['param'] . $this->options['kd100_key'] . $this->options['kd100_customer']));

        try {
            $params = [
                'base_uri' => $this->queryUrl,
                'timeout'  => 10,
            ];

            if (app()->isDebug()) {
                $params['verify'] = false;
            }

            $client = new Client($params);

            $response = $client->post('/poll/query.do', [
                'form_params' => $param,
            ]);
            $body     = (string)$response->getBody();
            $result   = json_decode($body, true);

            ShopLogHelper::info('快递100查询物流结果', ['params' => $params, 'result' => $result]);

            if (isset($result['returnCode']) || !isset($result['data'])) {
                ShopLogHelper::error('快递100查询物流失败', $result);
                $data = [];
            } else {
                $data = $this->formatData($result['data']);
            }
        } catch (Throwable $e) {
            // 异常处理
            ShopLogHelper::error('快递100查询物流失败', $params, $e);
            $data = [];
        }

        return $data;
    }

    public function formatData(array $data): array
    {
        return array_map(function ($item) {
            return ['time' => $item['ftime'], 'context' => $item['context']];
        }, $data);
    }
}